<?php

namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        HttpResponseException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     * @access public
     * @param Throwable $e
     * @return void
     */
    public function report(Throwable $e): void
    {
        if (!$this->isIgnoreReport($e)) {
            // 使用内置的方式记录异常日志
            parent::report($e);
        }
    }

    /**
     * Render an exception into an HTTP response.
     * @access public
     * @param $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 验证器异常
        if ($e instanceof ValidateException) {

            if($request->isAjax() || $request->isJson()){
                return json(['code' => 0, 'msg' => $e->getError()]);
            }else{
                return json(['code' => 0, 'msg' => $e->getError()]);
                return view(public_path() . 'tpl/500.tpl', ['message' => $e->getError()]);
            }
        }
        if (!($e instanceof HttpResponseException)) {
            return $this->tpl($request,$e);
        }
        return parent::render($request, $e);
    }

    /**
     * 异常模板
     * @param $request
     * @param Throwable $e
     * @return Response|\think\response\Json|\think\response\View
     */
    private function tpl($request, Throwable $e)
    {
        $appDebug = env('app_debug');
        if ($request->isAjax() || $request->isJson()) {
            if ($appDebug) {
                return json([
                    'code'  => 0,
                    'msg'   => $e->getMessage(),
                    'file'  => '[' . $e->getLine() . ']:' . $e->getFile(),
                    'trace' => $e->getTrace(),
                ]);
            } else {
                return json([
                    'code' => 0,
                    'msg'  => $e->getMessage()
                ]);
            }
        } else {
            if ($appDebug){
                return parent::render($request, $e);
            }else{
                return view(public_path() . 'tpl/500.tpl', ['message' => $e->getMessage()]);
            }
        }
    }
}
